#pragma once

#include <iostream>
#include <cstdio>
#include <string>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <sys/types.h>
#include <unistd.h>

#define ERR_EXIT(m)         \
    do                      \
    {                       \
        perror(m);          \
        exit(EXIT_FAILURE); \
    } while (0)

const int gdefaultid = -1;
const int gsize = 4096;
const std::string pathname = ".";
const int proj_id = 0x66;

#define CREATER "creater"
#define USER "user"

class Shm
{
private:
    int _shmid;
    int _size;
    key_t _key;
    std::string _usertype;
    void* _start_mem;// 共享内存首地址指针(挂接后的进程虚拟地址)

    void CreatShm(int flg)
    {
        _shmid = shmget(_key, _size, flg);
        if(_shmid < 0)
        {
            ERR_EXIT("shmget");
        }
        printf("shmid: %d\n", _shmid);
    }

    void Creat()
    {
        CreatShm(IPC_CREAT | IPC_EXCL | 0666);
    }

    void Get()
    {
        CreatShm(IPC_CREAT);
    }

    void Attach()
    {
        _start_mem = shmat(_shmid, nullptr, 0);
        if((long long)_start_mem < 0)
        {
            ERR_EXIT("shmat");
        }
        printf("attach success\n");
    }

    void Detach()
    {
        int n = shmdt(_start_mem);
        if(n < 0)
        {
            ERR_EXIT("shmdt");
        }
        printf("Detach success\n");
    }

    void Destroy()
    {
        Detach();
        if(_shmid == gdefaultid)
            return;
        if(_usertype == CREATER)
        {
            int n = shmctl(_shmid, IPC_RMID, NULL);
            if(n < 0)
            {
                ERR_EXIT("shmctl");
            }
            printf("shmctl delete shm: %d success!\n", _shmid);
        }
    }

public:
    Shm(const std::string& pathneme, int projid, const std::string& usertype)
        : _shmid(gdefaultid), _size(gsize), _start_mem(nullptr), _usertype(usertype)
    {
        _key = ftok(pathname.c_str(), projid);
        if (_key < 0)
        {
            ERR_EXIT("ftok");
        }
        printf("key: 0x%x\n", _key);

        if(_usertype == CREATER)
        {
            // 用户是服务端则创建共享内存段
            Creat();
        }
        else if(_usertype == USER)
        {
            // 用户是客户端则获取共享内存段
            Get();
        }

        Attach();
    }

    void* VirtualAddr()
    {
        printf("VirtualAddr: %p\n", _start_mem);
        return _start_mem;
    }

    int Size()
    {
        return _size;
    }

    ~Shm() 
    {
        Destroy();
    }
};
